$(document).ready(function(){
    //loadBooks();
    page(1);
});

function loadBooks(){
    $.getJSON("./JsonBooks").done(function(books){
        console.log(books);
        updateBooksView(books);
    }).fail(function(e){
        console.log(e);
    });
}

function updateBooksView(books){
    $("#shopView").empty();
    for(var book of books){
         var div=$("<div class='col-12 col-md-4 col-lg-3 mb-5'></div>");
         var a=$("<a class='product-item' href='./shoppingServlet?method=add&bookId="+book.id+"'></a>");
         a.append("<img class='img-fluid product-thumbnail' src='./images/upload/"+book.picture+"'>");
         a.append("<h3 class='product-title'>"+book.name+"</h3>");
         a.append("<h3 class='product-title'>"+book.author+"</h3>");
         a.append("<span>"+book.content+"<span><br>");
         a.append("<strong class='product-price'>"+"￥"+book.price+"</strong>");
         a.append("<span class='icon-cross'><img src='images/cross.svg' class='img-fluid'></span>");
         div.append(a);
         $("#shopView").append(div);
    }
}

function findByPage(curPage){
    $("li[name='liPage']").remove();
    page(curPage);
}

function leftQuery(){
    var curPage=$("li[class='active']").text();
    if(curPage==1) return;
    findByPage(parseInt(curPage)-1);
}

function rightQuery(){
    var curPage=$("li[class='active']").text();
    if(curPage==(($("li").length)-2)) return;
    findByPage(parseInt(curPage)+1);
}

function page(curPage){
    $.get(
    "queryPage",
    "page="+curPage,
    function(data){
        updateBooksView(data.books);
        for(var i=0;i<data.totalPages;i++){
            var $li=$("<li name='liPage'><a href='#' onclick='findByPage($(this).html())'>"+(i+1)+"</a></li>");
            $li.append("\xa0\xa0");
            //$("li:last").before($li);
            $(".pageul li:last").before($li);
            if(data.curPage==(i+1)){
                $li.attr("class","active");
            }
        }
    },
    "json"
    );
}

